package bkhech.generator.mybatis.util;

import bkhech.generator.mybatis.Constant;
import bkhech.generator.mybatis.domian.Generator;
import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.fastjson.JSON;
import com.esotericsoftware.yamlbeans.YamlReader;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Yaml Util
 *
 * @author guowm
 * @date 2022/8/10
 */
public final class YamlUtil {

    public static Generator parse() throws Exception {
        return parse(Constant.DEFAULT_CONFIG_FILE_NAME);
    }

    public static Generator parse(String configFileName) throws Exception {
        YamlReader yamlReader = readYml(configFileName);
        Object config = yamlReader.read();
        return JSON.parseObject(JSON.toJSONString(config), Generator.class);
    }

    private static YamlReader readYml(String configFileName) throws Exception {
        String readerLine;
        int lineNumber = 0;
        StringBuilder readString = new StringBuilder();
        ClassPathResource resource = new ClassPathResource(configFileName);

        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getStream()))) {
            while ((readerLine = bufferedReader.readLine()) != null) {
                lineNumber++;
                if (lineNumber > 1) {
                    readString.append(readerLine).append("\r\n");
                }
            }
        }
        return new YamlReader(readString.toString());
    }

}
